package util;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Random;

public class DataUtil {
	public static MinMaxIndexAndValue FindMinMax(ArrayList<Double> data, int begin, int end) {
		MinMaxIndexAndValue min_max = new MinMaxIndexAndValue();
		min_max.min = data.get(begin);
		min_max.max = data.get(begin);
		min_max.index_min = begin;
		min_max.index_max = begin;
		for (int i = begin; i <= end; ++i) {
			if (data.get(i) > min_max.max) {
				min_max.max = data.get(i);
				min_max.index_max = i;
			} else if (data.get(i) < min_max.min) {
				min_max.min = data.get(i);
				min_max.index_min = i;
			}
		}

		return min_max;
	}

	public static void OutputBooleanArray(Writer out, ArrayList<Boolean> array, int begin, int num) {
		try {
			boolean element = true;
			for (int i = begin; i < begin + num; ++i) {
				element = array.get(i);
				out.write(element ? "1" : "-1");
				out.write('\t');
			}

			out.write("\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static <T> void OutputArray(Writer out, ArrayList<T> array, int begin, int num) {
		try {
			T element = null;
			for (int i = begin; i < begin + num; ++i) {
				element = array.get(i);
				out.write(element.toString());
				out.write('\t');
			}

			out.write("\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static <T> ArrayList<ArrayList<T>> Transpose(ArrayList<ArrayList<T>> data) {
		ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>();
		for (int i = 0; i < data.get(0).size(); ++i) {
			result.add(new ArrayList<T>(data.size()));
		}

		for (ArrayList<T> anArray : data) {
			for (int j = 0; j < anArray.size(); ++j) {
				result.get(j).add(anArray.get(j));
			}
		}

		return result;
	}

	public static ArrayList<Integer> GetMRandsFromN(int m, int n) {
		assert (m > 0);
		assert (m <= n);

		ArrayList<Integer> result = new ArrayList<Integer>(m);
		ArrayList<Integer> all = new ArrayList<Integer>(n);
		for (int i = 0; i < n; ++i) {
			all.add(i);
		}

		int temp = 0;
		Random rand = new Random();
		for (int i = 0; i < m; ++i) {
			int index = rand.nextInt(n);
			temp = all.get(i);
			all.set(i, all.get(index));
			all.set(index, temp);
			result.add(all.get(i));
		}

		return result;
	}
}
